

import React, { useState, useEffect } from "react";
import { Table, Modal, Tag, Button, Typography, Popconfirm, Form, Input } from 'antd';
import type { TableColumnsType } from 'antd';

import { getNeedDetail, updateRouteByPlan } from "@/common/api"
import { TableRowSelection } from "antd/es/table/interface";

interface ChildProps {
    data: any,
    merge?: (values: any) => void;
    freshList?: () => void;
}


const SendDetail: React.FC<ChildProps> = ({ data, merge, freshList }) => {
    const [visible, setVisible] = useState(false)
    const [tableData, setTableData] = useState<any[]>([]);
    const [type, setType] = useState(null);
    useEffect(() => {
        setTableData([])
        if (data?.type == 2) {   //配送方案
            setVisible(true)
            setTableData(data.data)
            setType(data.type)
        }
        if (data?.type == 1) {  //配送需求
            setVisible(true)
            getData()
            setType(data.type)
        }
        if (data?.type == 3) {  //路线合并
            setVisible(true)
            setTableData(data.data)
            setType(data.type)
        }
    }, [data]);
    const getData = () => {
        let param = {
            needPlace: data.needPlace,
            pageSize: 300,
            pageNum: 1
        }
        getNeedDetail(param).then((res: any) => {
            if (res.success) {
                setTableData(res.data)
            }
        })

    }
    const handleCancel = () => {
        setVisible(false)
    }


    const getCell = (record: any, title: any, dataIndex: any) => {
        return {
            record,
            dataIndex: dataIndex,
            title: title,
            inputType: 'text',
            editing: isEditing(record),
        }
    }
    interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
        editing: boolean;
        dataIndex: string;
        title: any;
        inputType: 'number' | 'text';
        record: any;
        index: number;
    }
    const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{ margin: 0 }}
                        rules={[
                            {
                                required: false,
                                message: `请输入 ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    const columns2: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '接收单位',
            dataIndex: 'acceptUnit',
            // width: 150,
        },
        {
            title: '订单编号',
            dataIndex: 'orderCode',
            // width: 120,
        },
        {
            title: '订单重量(吨)',
            dataIndex: 'orderStowage',
            width: 120,
        },
        {
            title: '设备码',
            dataIndex: 'facilityCode',
            width: 120,
        },
        {
            title: '计划数量(只)',
            dataIndex: 'planNum',
            width: 120,
            onCell: (record) => (getCell(record, '计划数量(只)', 'planNum'))
        },
        {
            title: '设备描述',
            dataIndex: 'codeDescribe',
            width: 300,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            fixed: 'right',
            render: (_: any, record) => {
                const editable = isEditing(record);

                return editable ? (
                    <span>
                        <Typography.Link style={{ marginInlineEnd: 8 }} onClick={() => cancel()}>
                            取消
                        </Typography.Link>
                        <Popconfirm title="是否确认?" onConfirm={() => save(record)}>
                            <a>确认</a>
                        </Popconfirm>
                    </span>
                ) : (
                    <>
                        <Typography.Link onClick={() => edit(record)} style={{ marginRight: 16 }}>
                            编辑
                        </Typography.Link>


                    </>
                );


            },
        },

    ];
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: any) => record.id === editingKey;
    const [form] = Form.useForm();
    const cancel = () => {   //取消编辑
        setEditingKey('');
    };
    const edit = (record: any) => {
        form.setFieldsValue(record)
        setEditingKey(record.id);

    }
    const save = async (record: any) => {
        try {
            const row = await form.validateFields();
            updateRouteByPlan({ id: record.id, ...row }).then((res: any) => {
                if (res.success) {
                    $message.success(res.message);
                    setEditingKey('');
                    record.planNum = row.planNum
                    if (freshList) {
                        freshList()
                    }
                } else {
                    $message.error(res.message);
                }
            })

        } catch (errInfo) {
            console.log('验证失败:', errInfo);
        }
    }
    const columns: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '设备分类',
            dataIndex: 'facilityKind',
            width: 100,
        },
        {
            title: '设备码',
            dataIndex: 'facilityCode',
            width: 100,
        },
        {
            title: '设备描述',
            dataIndex: 'codeDescribe',
            width: 200,
        },

    ];
    const columns3: TableColumnsType = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            align: 'center' as const,
            onCell: () => ({ style: { textAlign: 'center' } }),
            render: (_text, _record, index) => index + 1,
        },
        {
            title: '路线',
            dataIndex: 'placeWay',
            // width: 100,
        },
        {
            title: '类型',
            dataIndex: 'markType',
            minWidth: 100,
            render: (text) => {
                let color = '';
                if (text == '拼车') {
                    color = '#7BAD8D';
                } else if (text == '整车') {
                    color = '#758DD1';
                }
                else if (text == '待拼车') {
                    color = '#F7B707';
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '配载(吨)',
            dataIndex: 'stowage',
            width: 100,
        },
        {
            title: '总重(吨)',
            dataIndex: 'totalLoad',
            width: 120,
        },
        {
            title: '总距离(km)',
            dataIndex: 'totalDistance',
            width: 120,
        },
        {
            title: '可补偿量',
            dataIndex: 'monthPlanFills',
            width: 120,
        },

    ];

    const tableConfig: any = {
        1: { columns: columns, rowKey: 'id' },
        2: { columns: columns2, rowKey: 'id' },
        3: { columns: columns3, rowKey: 'id' },
    };
    const currentConfig = tableConfig[type!];

    const [selectedRowKey, setSelectedRowKey] = useState<React.Key | null>(null);
    const rowSelection: TableRowSelection = {
        type: 'radio',
        selectedRowKeys: selectedRowKey ? [selectedRowKey] : [],
        onChange: (keys) => {
            setSelectedRowKey(keys.length ? keys[0] : null);
        },
    };
    const merges = () => {
        if (merge) {
            merge(selectedRowKey);
            setVisible(false)
        }
    }
    const getTable = () => {
        if (type == 1) {

        }
        if (type == 2) {
            return <div>
                <Form form={form} component={false}> <Table
                    components={{
                        body: { cell: EditableCell },
                    }}
                    bordered={true}
                    columns={currentConfig?.columns}
                    dataSource={tableData}
                    scroll={{ x: 'max-content' }}
                    pagination={false}
                    sticky={true}
                    rowKey={currentConfig?.rowKey}
                    style={{ height: '50vh', overflowY: 'auto', overflowX: 'hidden', width: '100%' }}
                /></Form>



            </div>

        }
        if (type == 3) {
            return <div>
                <Table
                    bordered={true}
                    columns={currentConfig?.columns}
                    dataSource={tableData}
                    scroll={{ x: 'max-content' }}
                    pagination={false}
                    sticky={true}
                    rowKey={currentConfig?.rowKey}
                    rowSelection={rowSelection}
                    style={{ height: '50vh', overflowY: 'auto', overflowX: 'hidden', width: '100%' }}
                />
                <div style={{ textAlign: 'center', marginTop: '20px' }}>
                    <Button type="primary" htmlType="submit" onClick={merges}>合并</Button>
                </div>
            </div>
        }

    }
    return <>
        <Modal
            title='详情'
            open={visible}
            width="80vw"
            footer={null}
            onCancel={handleCancel}
        >
            {/* <div>
                <Table
                    bordered={true}
                    columns={currentConfig?.columns}
                    dataSource={tableData}
                    scroll={{ x: 'max-content' }}
                    pagination={false}
                    sticky={true}
                    rowKey={currentConfig?.rowKey}
                    rowSelection={rowSelection}
                    style={{ height: '50vh', overflowY: 'auto', overflowX: 'hidden', width: '100%' }}
                />

                {type == 3 && <div style={{ textAlign: 'center', marginTop: '20px' }}>
                    <Button type="primary" htmlType="submit" onClick={merges}>合并</Button>
                </div>}


            </div> */}
            {getTable()}

        </Modal >
    </>
}


export default SendDetail